import * as echarts from 'echarts';
import ChartDataModelApi from "@/common/api/form/chartDataModel.js";
import FormCustomPublic from "../FormCustomPublic.js";
import FilterParams from "./FilterParams.vue"
import MapTypes from "./MapTypes.js";
import {ShareDialog} from "@lowcode/jpaas-share-component";
/**
 * 图表公共JS
 * @type {{methods: {}, props: {config: {type: Object}}}}
 */

const ChartPublic = {
    mixins:[FormCustomPublic,MapTypes],
    components:{
        FilterParams
    },
    data() {
        return {
            chartPie: null,
            //根据模型查询到的数据
            data: [],
            option:{},
            sql:"",
            //发布事件参数
            params:{},
            //图表过滤参数
            filterParams:[],
            //存放维度数据
            dimensionVals:[],
            //度量的数据
            measureVals:[],
            //存放颜色度量数据
            colorLegendVals:[],
            defColors:['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
        }
    },
    created() {
        let mapping = this.config.receive.mapping;
        if(mapping && mapping.length>0 ){
            //取路由参数
            let params=this.getRouterParams();
            for (let i = 0; i < mapping.length; i++) {
                let value="";
                if(this.config.receive.type=='url'){
                    if(mapping[i].valueSource=='param'){
                        if(params[mapping[i].valueDef]){
                            value=params[mapping[i].valueDef]
                        }else {
                            let arr = mapping[i].name.split(".");
                            let name=arr[arr.length-1];
                            if(params[name]){
                                value=params[name];
                            }
                        }
                    }
                }
                this.params[mapping[i].name]=value;
            }
        }
    },
    mounted() {
        let self=this;
        this.getParams(this.config.receive.mapping,function (res) {
            if(res){
                Object.assign(self.params,res);
            }
            self.initChart();
        })
    },
    methods: {
        /**
         * 初始化图表
         */
        initChart() {
            if(this.chartPie != null && this.chartPie != "" && this.chartPie != undefined) {
                this.chartPie.dispose();
            }
            let pieEl=this.$refs[this.config.alias];
            //初始化图表
            let language = window.localStorage.getItem('language');
            let locale=language=='en-US'? "EN":"ZH";
            this.chartPie = echarts.init(pieEl, 'macarons',{locale :locale});
            //自定义图表不用请求数据
            if(this.config.reportType=='customChart'){
                this.setOption();
                this.chartPie.resize();
                this.chartPie.setOption(this.option);
                return;
            }
            let measures=[];
            if(this.config.reportType=='lineBar'){
                for (let i = 0; i < this.config.measureList.length; i++) {
                    measures.push(...this.config.measureList[i]);
                }
            }else {
                measures=this.config.measures
            }
            let obj={
                dataModel:this.config.dataModel,
                colorLegends:this.config.colorLegends,
                measures:measures,
                dimensions:this.config.dimensions,
                params:this.params,
                filterParams:this.filterParams
            }
            let self=this;
            //获取数据
            ChartDataModelApi.getData(JSON.stringify(obj)).then(res => {
                if (res.data && res.data.length > 0) {
                    this.data = res.data;
                    this.sql = res.sql;
                    //获取初始化数据
                    this.getInitData();
                    this.setOption();
                    //是否开启联动
                    if(this.config.advConfig.linkage){
                        //图表点击节点回调事件
                        this.chartPie.on('click',function(params){
                            let publishParams={
                                component:self.config.alias,
                            };
                            if(self.config.publish){
                                //弹窗
                                if(self.config.publish.publishType=="window"){
                                    let windowConfig = self.config.publish.windowConfig;
                                    self.windowDialog(windowConfig,params);
                                }else {
                                    //发事件
                                    if(self.config.publish.paramMapping.length>0){
                                        //未配置颜色图例直接去查data的数据
                                        if(self.config.colorLegends.length==0){
                                            publishParams.params= self.getParamsByData(params);
                                        }else {
                                            publishParams.params= self.getParamsByConfig(params);
                                        }
                                    }
                                    self.$bus.emit("formCustomViewEvent",publishParams);
                                }
                            }
                        });
                    }
                    this.chartPie.resize();
                    this.chartPie.setOption(this.option);
                }
            });
        },
        //获取初始化数据
        getInitData(){
            //维度
            this.dimensionVals=[];
            for (let i = 0; i < this.config.dimensions.length; i++) {
                let dimension = this.config.dimensions[i];
                for (let j = 0; j < this.data.length; j++) {
                    let dimensionVal =this.data[j][dimension.tableName+'_'+dimension.fieldName] || "";
                    if(typeof(dimensionVal)!='string'){
                        dimensionVal=dimensionVal.newValue || "";
                    }
                    let number = this.dimensionVals.indexOf(dimensionVal);
                    if(number==-1) {
                        this.dimensionVals.push(dimensionVal);
                    }
                }
            }
            //度量
            this.measureVals=[];
            for (let i = 0; i < this.config.measures.length; i++) {
                let measure = this.config.measures[i];
                for (let j = 0; j < this.data.length; j++) {
                    let measureVal =this.data[j][measure.tableName+'_'+measure.fieldName];
                    let number = this.measureVals.indexOf(measureVal);
                    if(number==-1) {
                        this.measureVals.push({
                            key:measure.tableName+'.'+measure.fieldName,
                            value:measureVal
                        });
                    }
                }
            }
            //颜色图例
            this.colorLegendVals=[];
            for (let i = 0; i < this.config.colorLegends.length; i++) {
                let colorLegend = this.config.colorLegends[i];
                for (let j = 0; j < this.data.length; j++) {
                    let colorValue =this.data[j][colorLegend.tableName+'_'+colorLegend.fieldName];
                    let number = this.colorLegendVals.indexOf(colorValue);
                    if(number==-1) {
                        this.colorLegendVals.push(colorValue);
                    }
                }
            }
        },
        //获取维度
        getDimensions(xAxisArr){
            let xAxisData=[];
            for (let i = 0; i < this.data.length; i++) {
                let xAxisValue="";
                let oldValue="";
                let key="";
                //维度
                for (let j = 0; j < this.config.dimensions.length; j++) {
                    let dimension = this.config.dimensions[j];
                    if(xAxisValue==""){
                        xAxisValue=this.data[i][dimension.tableName+'_'+dimension.fieldName] || "";
                        if(typeof(xAxisValue)!='string'){
                            oldValue=xAxisValue.oldValue || "";
                            xAxisValue=xAxisValue.newValue || "";
                        }
                        key=dimension.tableName+'_'+dimension.fieldName;
                    }else {
                        let val=this.data[i][dimension.tableName+'_'+dimension.fieldName] || "";
                        if(typeof(val)!='string'){
                            oldValue=xAxisValue+"-"+val.oldValue || "";
                            xAxisValue+=xAxisValue+"-"+val.newValue || "";
                        }else {
                            oldValue+="-"+val;
                            xAxisValue+="-"+val;
                        }
                        key+="-"+dimension.tableName+'_'+dimension.fieldName
                    }
                }
                let number = xAxisData.indexOf(xAxisValue);
                if(number==-1){
                    xAxisData.push(xAxisValue);
                }
                if(xAxisArr){
                    if(oldValue){
                        let item = xAxisArr.find((info) => info.value == oldValue )
                        if(!item){
                            xAxisArr.push({
                                key:key,
                                value:oldValue
                            });
                        }
                    }else {
                        let item = xAxisArr.find((info) => info.value == xAxisValue )
                        if(!item){
                            xAxisArr.push({
                                key:key,
                                value:xAxisValue
                            });
                        }
                    }

                }
            }
            let xAxis={
                data: xAxisData,
                axisLine: {
                    show: true,
                    lineStyle: {
                        color:this.config.advConfig.xAxisColor?this.config.advConfig.xAxisColor:"#333"
                    }
                },
            }
            return xAxis;
        },
        //根据data取参数
        getParamsByData(clickObj){
            let params= {};
            let paramMapping=this.config.publish.paramMapping;
            //地图 点击对象无数据则给null
            if(this.config.reportType=="map" && !clickObj.data ){
                for (let i = 0; i < paramMapping.length; i++) {
                    if(paramMapping[i].key=="mapType_"){
                        params[paramMapping[i].key]=clickObj.name;
                    } else if(!params[paramMapping[i].key]){
                        params[paramMapping[i].key]="null";
                    }
                }
                return params;
            }
            for (let i = 0; i <paramMapping.length ; i++) {
                let value="";
                if(paramMapping[i].key=="mapType_"){
                    value=clickObj.name;
                }else {
                    let key = (paramMapping[i].key).replace(".","_");
                    value = this.data[clickObj.dataIndex][key];
                }
                if(!value){
                    continue;
                }
                //配置了字段渲染
                if(typeof(value) !="string"){
                    params[paramMapping[i].key]=value.oldValue;
                }else {
                    params[paramMapping[i].key]=value;
                }
            }
            return params;
        },
        //根据配置取参数 clickObj:点击的对象
        getParamsByConfig(clickObj){
            let params= {};
            let paramMapping=this.config.publish.paramMapping;
            //地图 点击对象无数据则给null
            if(this.config.reportType=="map" && !clickObj.data ){
                for (let i = 0; i < paramMapping.length; i++) {
                    if(paramMapping[i].key=="mapType_"){
                        params[paramMapping[i].key]=clickObj.name;
                    } else if(!params[paramMapping[i].key]){
                        params[paramMapping[i].key]="null";
                    }
                }
                return params;
            }
            for (let i = 0; i <paramMapping.length ; i++) {
                let value="";
                //地图类型
                if(paramMapping[i].key=="mapType_"){
                    value=clickObj.name;
                    params[paramMapping[i].key]=value;
                    continue;
                }
                //维度
                for (let j = 0; j < this.config.dimensions.length; j++) {
                    let dimension = this.config.dimensions[j];
                    let key=dimension.tableName+"."+dimension.fieldName;
                    if(paramMapping[i].key==key){
                        let dimensionVal = this.dimensionVals[clickObj.dataIndex];
                        if(dimensionVal){
                            //配置了字段渲染
                            if(typeof(dimensionVal) !="string" && typeof(value) !="number"){
                                value=dimensionVal.oldValue;
                            }else {
                                value=dimensionVal;
                            }
                            break;
                        }
                    }
                }
                if(value!=""){
                    params[paramMapping[i].key]=value;
                    continue;
                }
                //度量
                for (let j = 0; j < this.config.measures.length; j++) {
                    let measure = this.config.measures[j];
                    let key=measure.tableName+"."+measure.fieldName;
                    if(paramMapping[i].key==key){
                        let index=(clickObj.dataIndex+1) * (clickObj.componentIndex+1);
                        if(this.measureVals[index] && this.measureVals[index-1].key==paramMapping[i].key){
                            value= this.measureVals[index].value;
                        }
                    }
                }
                if(value!=""){
                    params[paramMapping[i].key]=value;
                    continue;
                }
                //颜色图例
                for (let j = 0; j < this.config.colorLegends.length; j++) {
                    let colorLegend = this.config.colorLegends[j];
                    let key=colorLegend.tableName+"."+colorLegend.fieldName;
                    if(paramMapping[i].key==key){
                        let index=(clickObj.componentIndex)%this.colorLegendVals.length;
                        value=this.colorLegendVals[index];
                    }
                }
                if(value!=""){
                    params[paramMapping[i].key]=value;
                    continue;
                }

            }
            return params;
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys
        },
        /**
         *
         */
        addParams() {
            // if (this.config.receive.mapping.length >= this.listParamsDef.length) {
            //     this.$notification.warning({
            //         message: '提示信息',
            //         description: '该数据列表未配置传入参数，请去配置!',
            //     })
            //     return
            // }
            this.config.receive.mapping.push({ idx_: Util.randomId(), name: '', valueSource: '', valueDef: '' })
        },
        moveUp() {
            this.toUp(this.config.receive.mapping, this.selectedRowKeys)
        },
        moveDown() {
            this.toDown(this.config.receive.mapping, this.selectedRowKeys)
        },
        removeSelect() {
            this.removeRows(this.config.receive.mapping, this.selectedRowKeys)
        },
        //处理接收到的事件
        handReceive(args) {
            let receive = this.config.receive;
            //地图类型配置
            let mapTypeConf = this.config.mapTypeConf;
            if ( (receive.type=='event' &&receive.publishComponent == args.component) || (mapTypeConf && mapTypeConf.component == args.component)) {
                let inputParams = args.params;
                let params = {};
                //读取配置的参数
                for (let i = 0; i < receive.mapping.length; i++) {
                    let o = receive.mapping[i];
                    //处理没有配置值来源的情况。
                    if(!o.valueDef && inputParams[o.name]){
                        params[o.name]=inputParams[o.name]
                    }
                    else if (o.valueSource == 'param' && inputParams[o.valueDef]) {
                        params[o.name] = inputParams[o.valueDef];
                    }
                }
                this.params=params;
                if(mapTypeConf && mapTypeConf.valueDef){
                    let mapType= this.mapTypes.find(item=>item.label==inputParams[mapTypeConf.valueDef]);
                    this.config["mapType_"]=mapType?mapType.value:"";
                }
                //初始化图表
                this.initChart();
            }
        },
        //图表过滤条件查询
        paramsChange(params){
            this.filterParams=[];
            for (let i = 0; i <params.length ; i++) {
                let value = params[i].value;
                if(value){
                    this.filterParams.push({
                        key:params[i].tableName+"."+params[i].fieldName,
                        value:value,
                        controlType:params[i].condition.controlType,
                        opType:params[i].condition.opType
                    })
                }
            }
            //初始化图表
            this.initChart();
        },
        //获取颜色维度值
        getColorValue(data,colorLegend,measure){
            let colorValue="";
            //是否拼接度量的值 多个度量必须拼接
            if(this.config.advConfig.joinMeasure || this.config.measures.length>1){
                colorValue=data[colorLegend.tableName+'_'+colorLegend.fieldName]+"-"+measure.fieldLabel;
            }else {
                colorValue =data[colorLegend.tableName+'_'+colorLegend.fieldName];
            }
            return colorValue;
        },
        getColors(){
            //颜色配置
            let colors=this.defColors;
            if(this.config.colour.content && this.config.colour.content.length>0 ){
                colors=this.config.colour.content;
            }
            return colors;
        },
        handPublicReceive(args){
            //通过自定义的事件
            if(args && args.type=="custom" && args.params){
                this.params=args.params;
                //初始化图表
                this.initChart();
                return;
            }
            let receive = this.config.receive;
            let inputParams = args.params;
            let params = {};
            //读取配置的参数
            for (let i = 0; i < receive.mapping.length; i++) {
                let o = receive.mapping[i];
                params[o.name]=inputParams[o.valueDef]
            }
            this.params=params;
            //初始化图表
            this.initChart();
        },
        /**
         * 弹窗
         * @param windowConfig
         * { type:"list",
             setting:"",
             publishParams:[]}
         * @param clickObj 点击传递的数据
         */
        windowDialog(windowConfig,clickObj){
            if(windowConfig.setting){
                let setting = eval("(" + windowConfig.setting +")")
                setting.text
                let parameter={
                    key:setting.value,
                    params:""
                }
                let params={}
                if(windowConfig.publishParams){
                    for (var i = 0; i <windowConfig.publishParams.length ; i++) {
                        let publishParams =windowConfig.publishParams[i];
                        var value="";
                        if(publishParams.valueDef){
                            let key = (publishParams.valueDef).replace(".","_");
                            value = this.data[clickObj.dataIndex][key];
                        }
                        if(!value){
                            continue;
                        }
                        //配置了字段渲染
                        if(typeof(value) !="string" && typeof(value) !="number"){
                            params[publishParams.listParam]=value.oldValue;
                        }else {
                            params[publishParams.listParam]=value;
                        }
                    }
                    var aryParams=[];
                    for(var key in params){
                        aryParams.push(key + "=" + params[key]);
                    }
                    parameter.params=aryParams.join("&");
                }
                ShareDialog.dialog(parameter,{curVm:this,max:true});
            }
        }
    },
    watch:{
        option:{
            handler: function (val, oldVal) {
                let self=this;
                self.chartPie.setOption(val);
            },
            deep: true
        },
        config:{
            handler: function (val, oldVal) {
                let self=this;
                setTimeout(function () {
                    self.$emit("setChartComponent",val);
                    self.initChart();
                },2000)
            },
            deep: true
        }
    }

}

export default ChartPublic;
